<?php
namespace app\api\controller;

use app\BaseController;
//use app\api\model\BbsModel;
use app\api\model\MemberModel as MemberModel;
use think\Db;

//use app\Config;


class Wechart extends BaseController {


	/**
	 * openid
	 */
	function jscode2session()
	{
		$code = $this->getParam("code");
		
		if(!$this->pvalidate(["code"=>$code],["code"],["req"],["需要jscode "])){//校验
			return;
		}
		$appId = config("appId");
    		$appSecret = config("appSecret");
			
		$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appId.'&secret='.$appSecret.'&js_code='.$code.'&grant_type=authorization_code';  
	    
	    $arr = doGet($url);//发送HTTPs请求并获取返回的数据，推荐使用curl
	    
	    $arr['timestamp'] = time();
		
		if(isset($arr['openid'])){
			$openid = $arr["openid"];
			$findMember = Db::name('t_member')->where('openid', $openid)->find();
			if(!empty($findMember)){
				$memberId = $findMember['id'];
				
				$userToken = Db::name("t_user_token")->where("memberId",$memberId)->find();
				if(empty($userToken) || $userToken["expireTime"]<time()){
					//创建新的
					$userToken = $this->generalToken($memberId,$findMember['phone'], time());
					$userToken["memberId"] = $memberId;
						
			    		$memberModel = new MemberModel();
					$memberModel->updateUserToken($userToken);	
				}else{
					//重新设置token时间  如果要更改7200的话，则
					$userToken["expireTime"] = time()+7200;
					Db::name("t_user_token")->where("id",$userToken["id"])->update(["expireTime"=>($userToken["expireTime"])]);
				}
				
				$arr['memberId']=$memberId;
				$arr['token']=$userToken['token'];
				$arr['expireTime']=$userToken['expireTime'];
				
			}
		}
				
		echo json_encode(array("success"=>1,"content"=>_unsetNull($arr),"code"=>200,"msg"=>"ok"),true);
	}	
	
	
}
